﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using KC.Framework.Util;

namespace KC.Common.HttpHelper
{
    public static class HttpHelp
    {
        /// <summary>
        /// 通过post方式
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <param name="requestEncoding"></param>
        /// <param name="CertFilePath"></param>
        /// <returns></returns>
        public static string CreatePostHttpResponse(string url, IDictionary<string, object> parameters, Encoding requestEncoding, string CertFilePath)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("接口地址为空");
            }
            if (requestEncoding == null)
            {
                requestEncoding = Encoding.UTF8;
            }
            HttpWebRequest request = null;
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateValidationCallback;
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
            request.UserAgent = "Mozilla/4.0";
            request.KeepAlive = true;
            request.Timeout = 60000;

            string newtonstr = SerializeHelper.ToJson(parameters);
            if (!(parameters == null || parameters.Count == 0))
            {
                //StringBuilder buffer = new StringBuilder();
                //int i = 0;
                //foreach (string key in parameters.Keys)
                //{
                //    if (i > 0)
                //    {
                //        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                //    }
                //    else
                //    {
                //        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                //    }
                //    i++;
                //}
                string result = GetRsaByteData(newtonstr, requestEncoding, CertFilePath);
                result = result.Replace("+", "%2B");
                string dd = "data=" + result + "";
                //byte[] data = Encoding.GetEncoding("utf-8").GetBytes(dd);
                byte[] data = requestEncoding.GetBytes(dd);
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            try
            {
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    var st = response.GetResponseStream();
                    if (st == null)
                    {
                        throw new Exception("获取远程返回结果失败");
                    }
                    using (var reader = new StreamReader(st, Encoding.UTF8))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
            catch (Exception)
            {
                return "";
            }

        }
        public static bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;
            return false;
        }
        /// <summary>
        /// 公钥加密
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="cerFilePath"></param>
        /// <returns></returns>
        //public static string GetRsaByteData(string data, Encoding requestEncoding, string cerFilePath)
        //{
        //    X509Certificate2 myX509Certificate2 = new X509Certificate2(cerFilePath);
        //    RSACryptoServiceProvider myRsaCryptoServiceProvider =
        //        (RSACryptoServiceProvider)myX509Certificate2.PublicKey.Key;
        //    //byte[] barry = Encoding.Default.GetBytes(data);
        //    byte[] barry = requestEncoding.GetBytes(data);
        //    Byte[] Cryptograph = myRsaCryptoServiceProvider.Encrypt(barry, false);
        //    return Convert.ToBase64String(Cryptograph);
        //}
        /// <summary>
        /// 分段加密
        /// </summary>
        /// <param name="data"></param>
        /// <param name="requestEncoding"></param>
        /// <param name="cerFilePath"></param>
        /// <returns></returns>
        public static String GetRsaByteData(string data, Encoding requestEncoding, string cerFilePath)
        {
            X509Certificate2 myX509Certificate2 = new X509Certificate2(cerFilePath);
            using (RSACryptoServiceProvider RSACryptography = (RSACryptoServiceProvider)myX509Certificate2.PublicKey.Key)
            {
                Byte[] PlaintextData = requestEncoding.GetBytes(data);
                int MaxBlockSize = RSACryptography.KeySize / 8 - 11;    //加密块最大长度限制

                if (PlaintextData.Length <= MaxBlockSize)
                    return Convert.ToBase64String(RSACryptography.Encrypt(PlaintextData, false));

                using (MemoryStream PlaiStream = new MemoryStream(PlaintextData))
                using (MemoryStream CrypStream = new MemoryStream())
                {
                    Byte[] Buffer = new Byte[MaxBlockSize];
                    int BlockSize = PlaiStream.Read(Buffer, 0, MaxBlockSize);

                    while (BlockSize > 0)
                    {
                        Byte[] ToEncrypt = new Byte[BlockSize];
                        Array.Copy(Buffer, 0, ToEncrypt, 0, BlockSize);

                        Byte[] Cryptograph = RSACryptography.Encrypt(ToEncrypt, false);
                        CrypStream.Write(Cryptograph, 0, Cryptograph.Length);

                        BlockSize = PlaiStream.Read(Buffer, 0, MaxBlockSize);
                    }

                    return Convert.ToBase64String(CrypStream.ToArray(), Base64FormattingOptions.None);
                }
            }
        }
        public static string EncodeBase64(Encoding encoding, string source)
        {
            string data = "";
            byte[] bytes = encoding.GetBytes(source);
            try
            {
                data = Convert.ToBase64String(bytes);
            }
            catch
            {

            }
            return data;
        }
        public static string EncodeBase64(string source)
        {
            return EncodeBase64(Encoding.UTF8, source);
        }

        public static async Task<Tuple<bool, string>> WebClientDownloadAsync(string url, string postString)
        {
            byte[] postData = Encoding.UTF8.GetBytes(postString);
            var webClient = new WebClient();
            webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            try
            {
                byte[] responseData = await webClient.UploadDataTaskAsync(url, "POST", postData);
                return new Tuple<bool, string>(true, Encoding.UTF8.GetString(responseData));
            }
            catch (Exception ex)
            {
                LogUtil.LogException(ex);
                return new Tuple<bool, string>(false, ex.Message);
            }
        }

        public static Tuple<bool, string> WebClientDownload(string url, string postString)
        {
            byte[] postData = Encoding.UTF8.GetBytes(postString);
            var webClient = new WebClient();
            webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            try
            {
                byte[] responseData = webClient.UploadData(url, "POST", postData);
                return new Tuple<bool, string>(true, Encoding.UTF8.GetString(responseData));
            }
            catch (Exception ex)
            {
                LogUtil.LogException(ex);
                return new Tuple<bool, string>(false, ex.Message);
            }
        }

        public static Tuple<bool, string> WebClientDownloadText(string url, string postString)
        {
            byte[] postData = Encoding.UTF8.GetBytes(postString);
            var webClient = new WebClient();
            webClient.Headers.Add("Content-Type", "text/plain");
            try
            {
                byte[] responseData = webClient.UploadData(url, "POST", postData);
                return new Tuple<bool, string>(true, Encoding.UTF8.GetString(responseData));
            }
            catch (Exception ex)
            {
                LogUtil.LogException(ex);
                return new Tuple<bool, string>(false, ex.Message);
            }
        }


        public static Tuple<bool, string> WebClientDownloadXMLData(string url, string postXMLString)
        {
            byte[] postData = Encoding.UTF8.GetBytes(postXMLString);
            var webClient = new WebClient();
            webClient.Headers.Add("Content-Type", "text/xml");
            try
            {
                byte[] responseData = webClient.UploadData(url, "POST", postData);
                return new Tuple<bool, string>(true, Encoding.UTF8.GetString(responseData));
            }
            catch (Exception ex)
            {
                LogUtil.LogException(ex);
                return new Tuple<bool, string>(false, ex.Message);
            }
        }

        public static Tuple<bool, string> WebClientDownloadXMLData1(string url, string postString)
        {
            var en = Encoding.GetEncoding("GB2312");
            byte[] postData = en.GetBytes(postString);
            var webClient = new WebClient();
            webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            try
            {
                byte[] responseData = webClient.UploadData(url, "POST", postData);
                return new Tuple<bool, string>(true, en.GetString(responseData));
            }
            catch (Exception ex)
            {
                LogUtil.LogException(ex);
                return new Tuple<bool, string>(false, ex.Message);
            }
        }

        public static byte[] WebClientDownload(string url)
        {
            var webClient = new WebClient();
            try
            {
                webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
                byte[] responseData = webClient.DownloadData(url);
                return responseData;
            }
            catch (Exception ex)
            {
                LogUtil.LogException(ex);
                return null;
            }
        }

        public static void OpenUrl(string url)
        {
            try
            {
                var req = (HttpWebRequest)WebRequest.Create(url);
                req.KeepAlive = false;
                req.Timeout = 15;
                req.GetResponse();
            }
            catch (Exception)
            {
               
            }
        }

        //public static bool IsWX(System.Web.HttpRequestBase request)
        //{
        //    if (request == null || request.UserAgent == null)
        //        return false;
        //    if (request.UserAgent.Contains("MicroMessenger"))
        //    {
        //        return true;
        //    }
        //    return false;
        //}
    }
}
